package com.crm.CLdriving.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.crm.CLdriving.common.BaseResponse;
import com.crm.CLdriving.common.PageResponse;
import com.crm.CLdriving.dto.PageReq.PageNumber;
import com.crm.CLdriving.dto.resp.CoachSelectAllRespDto;
import com.crm.CLdriving.enu.ResponseEnum;
import com.crm.CLdriving.vo.NewsCondition;
import com.crm.CLdriving.po.NewsPO;
import com.crm.CLdriving.service.NewsService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("news")
@AllArgsConstructor
@Log4j2
public class NewsController {

    private final NewsService newsService;
    /**
     * 加载文章列表
     * @param newsConditionVo
     * @return
     */
    @GetMapping("list")
    @ResponseBody
    public PageResponse<List<NewsPO>> loadArticle(NewsCondition newsConditionVo) {
        newsConditionVo.setSliderFlag(true);
        Page<NewsPO> page = new Page<>(newsConditionVo.getPageNumber(), newsConditionVo.getPageSize());
        List<NewsPO> articleList = newsService.findByCondition(page, newsConditionVo);
        return PageResponse.successOfPage(articleList,page);
    }

    @PostMapping("all")
    @ResponseBody
    @ApiOperation("查询 全部新闻接口")
    public PageResponse<List<NewsPO>> SelectAll(@RequestBody PageNumber pageNumber) {
        return newsService.selectAll(pageNumber);
    }

    @PostMapping("/add")
    @ResponseBody
    @ApiOperation("录入新闻接口")
    public BaseResponse<?> add(@Valid @RequestBody NewsPO newsPO) {
        log.info(""+JSON.toJSONString(newsPO));
        try {
            newsService.insertArticle(newsPO);
            return BaseResponse.message(ResponseEnum.SUCCESS);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return BaseResponse.message(ResponseEnum.FAIL);
        }
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public BaseResponse<?> delete(Integer id) {
        return deleteBatch(new Integer[]{id});
    }

    @DeleteMapping("/batch/delete")
    @ResponseBody
    public BaseResponse<?> deleteBatch(@RequestParam("ids") Integer[] ids) {
        int i = newsService.deleteBatch(ids);
        if (i > 0) {
            return BaseResponse.message(ResponseEnum.SUCCESS);
        } else {
            return BaseResponse.message(ResponseEnum.FAIL);
        }
    }
}
